package com.tdd.api.server.base.util;

import cn.hutool.core.util.StrUtil;
import com.google.common.collect.Maps;
import org.springframework.stereotype.Component;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 *  @author lvchangbin
 *  @create 2018-12-06 15:46
 */
@Component
public class CookieUtil {

    /**
     * 获取List<map>
     * @param request
     * @return
     */
    public Map<String,String> getCookies(HttpServletRequest request){
        Cookie[] cookies = request.getCookies();
        if(cookies == null){
            return null;
        }
        Map<String,String > map= Maps.newHashMap();
        for(Cookie cookie : cookies){
            map.put(cookie.getName(),cookie.getValue());
        }
        return map;
    }

    /**
     * 获取
     * @param request
     * @return
     */
    private String getCookiesString(HttpServletRequest request){
        Cookie[] cookies = request.getCookies();
        if(cookies == null){
            return "";
        }
        StringBuilder cookieHeader = new StringBuilder();
        for(Cookie cookie : cookies){
            cookieHeader.append(cookie.getName()).append("=").append(cookie.getValue());
        }
        return cookieHeader.toString();
    }

    /**
     * 获取Cookie信息ß
     *
     * @param request
     * @param key
     * @return
     */
    public static Cookie get(HttpServletRequest request, String key) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0) {
            for (Cookie ck : cookies) {
                if (StrUtil.equals(key, ck.getName())) {
                    return ck;
                }
            }
        }
        return null;
    }
    /**
     * 删除Cookie
     *
     * @param request
     * @param response
     * @param domain
     * @param key
     */
    public static void removeCookie(HttpServletRequest request,
                                    HttpServletResponse response, String domain, String key) {
        Cookie cookie = get(request, key);
        if (cookie != null) {
            cookie.setMaxAge(0);
            cookie.setPath("/");
            cookie.setDomain(domain);
            response.addCookie(cookie);
        }
    }
}
